<template>
  <div class="employees-container">
    <div class="app-container">
      <page-tools>
        <template #left>
          <span>总记录数: {{ total }} 条</span>
        </template>
        <template #right>
          <el-button
            v-input="'aa'"
            type="warning"
            size="small"
            @click="$router.push('/import')"
          >excel导入</el-button>
          <el-button
            v-input="'aa'"
            type="danger"
            size="small"
            @click="handleDownload"
          >excel导出</el-button>
          <el-button v-input=" 'aa' " type="primary" size="small" @click="showDialog = true">新增员工</el-button>
        </template>
      </page-tools>

      <el-card style="margin-top: 10px;">
        <!-- 渲染数据 -->
        <el-table
          :default-sort="{prop: 'timeOfEntry', order: 'descending'}"
          border
          :data="list"
        >
          <el-table-column label="序号" width="80" type="index" />
          <el-table-column label="姓名" prop="username" />
          <el-table-column sortable label="工号" prop="workNumber" />
          <el-table-column label="聘用形式" prop="formOfEmployment">
            <template #default="{row}">
              {{ enumerate(row.formOfEmployment) }}
            </template>
          </el-table-column>
          <el-table-column label="部门" prop="departmentName" />
          <el-table-column
            sortable
            label="入职时间"
            prop="timeOfEntry"
          />
          <!-- <el-table-column label="账户状态" /> -->
          <el-table-column label="操作" width="280">
            <template #default="{row}">
              <el-button type="text" size="small" @click="$router.push(`/employees/detail/${row.id}`)">查看</el-button>
              <el-button type="text" size="small" @click="clickAssign(row.id)">分配角色</el-button>
              <el-button type="text" size="small" @click="del(row.id)">删除</el-button>
            </template>
          </el-table-column>
        </el-table>
        <!-- 分页组件 -->
        <el-row type="flex" justify="center" align="middle" style="height: 60px">
          <el-pagination
            :current-page="pagination.page"
            :page-sizes="[2, 4, 6, 8,10]"
            :page-size="pagination.size"
            layout="total, sizes, prev, pager, next, jumper"
            :total="total"
            @size-change="handleSizeChange"
            @current-change="handleCurrentChange"
          />
        </el-row>
      </el-card>
      <!-- 添加员工弹层 -->
      <el-dialog
        title="添加员工"
        :visible.sync="showDialog"
        :close-on-press-escape="false"
        :close-on-click-modal="false"
        @close="Hclose"
      >
        <empDialog ref="resetForm" @close="showDialog=false" @success="Hsuccess" />
      </el-dialog>
      <!-- 分配角色弹层 -->
      <el-dialog
        title="分配角色"
        :close-on-press-escape="false"
        :close-on-click-modal="false"
        :visible.sync="showDialogRole"
      >
        <assignRole v-if="showDialogRole" :role-id="roleId" @close="showDialogRole = false" />
      </el-dialog>
    </div>
  </div>
</template>
<script>
import assignRole from './assignRole'
import empDialog from './empDialog'
import { getUserAll, delEmployee } from '@/api/employees'

// 枚举格式
import employees from '@/constant/employees.js'
console.log('employees.hireType', employees.hireType)
// 枚举
const num = employees.hireType.reduce((acc, item) => {
  acc[item.id] = item.value
  return acc
}, {})
console.log('枚举后的num', num)
export default {
  components: {
    empDialog, assignRole
  },
  data() {
    return {
      roleId: null, // 保存分配角色被点击元素的id
      showDialogRole: false, // 控制分配角色弹层
      showDialog: false, // 控制添加员工弹层的显示隐藏
      list: [], // 保存企业部门列表
      // 用来做分页发送的数据
      pagination: {
        page: 1, // 当前第几页
        size: 2 // 每页显示几条数据
      },
      total: 0 // 用来保存总的数据
    }
  },
  created() {
    this.loadUserAll()
  },
  methods: {
    // 每页几条数据
    handleSizeChange(val) {
      console.log(`每页 ${val} 条`)
      this.pagination.page = 1
      this.pagination.size = val
      this.loadUserAll()
    },
    // /当前第几页
    handleCurrentChange(val) {
      console.log(`当前页: ${val}`)
      this.pagination.page = val
      this.loadUserAll()
    },
    // 获取企业部门列表
    async loadUserAll() {
      try {
        const res = await getUserAll(this.pagination)
        // console.log('getUserAll', res)
        if (res.code !== 10000) return
        // 保存数据
        this.total = res.data.total
        this.list = res.data.rows
      } catch (err) {
        console.log('getUserAll', err)
      }
    },
    // 枚举格式
    enumerate(data) {
      return num[data] || '未知'
    },
    // 监听子组件抛出事件的回调函数
    Hsuccess() {
      this.showDialog = false
      this.total++
      this.pagination.page = Math.ceil(this.total / this.pagination.size)
      this.loadUserAll()
    },
    // dialog 弹层关闭时的回调函数
    Hclose() {
      this.$refs.resetForm.reset()
    },
    // 点击了删除
    del(id) {
      this.$confirm('你点击了删除,是否继续?', '提示').then(async() => {
        try {
          const res = await delEmployee(id)
          // console.log('delEmployee', res)
          // 保存数据
          if (res.code !== 10000) return
          this.$message.success(res.message)
          if (this.list.length === 1) {
            this.pagination.page--
            if (this.pagination.page < 0) {
              this.pagination.page = 1
            }
          }
          this.loadUserAll()
        } catch (err) {
          console.log('delEmployee', err)
        }
      }).catch(err => console.log(err))
    },
    // 点击 excel批量导出执行的函数
    async  handleDownload() {
      // 获取员工列表
      try {
        const res = await getUserAll(this.pagination)
        console.log('getUserAll', res)
        // 保存数据
        if (res.code !== 10000) return
        const { header, data } = this.dataFormt(res.data.rows)
        // 进行数据导出
        import('@/vendor/Export2Excel').then(excel => {
          excel.export_json_to_excel({
            header: header,
            data,
            filename: this.filename,
            autoWidth: this.autoWidth,
            bookType: this.bookType
          })
        })
      } catch (err) {
        console.log('getUserAll', err)
      }
    },
    // 导出excel 格式转换数据
    dataFormt(list) {
      // Object.values(item)  ["2018-11-20"]
      // 1. 根据数据对象的健根据映射关系，得到一个中文的健，放到一个数组中  ---header ['编号', '密码']
      // 2. 将每一个对象的值，存到一个数组中，所有的结果放入到一个大的数组中--data  [["2018-11-30", "总裁办"],[]]
      const map = {
        'id': '编号',
        'password': '密码',
        'mobile': '手机号',
        'username': '姓名',
        'timeOfEntry': '入职日期',
        'formOfEmployment': '聘用形式',
        'correctionTime': '转正日期',
        'workNumber': '工号',
        'departmentName': '部门',
        'staffPhoto': '头像地址'
      }
      const one = list[0]
      if (one) {
        let header = []
        const enkeys = Object.keys(one)
        // console.log('enkeys---------', enkeys)
        header = enkeys.map(enkey => {
          return map[enkey]
        })
        // console.log('header-----', header)
        // console.log('  Object.keys(one)', Object.keys(one))
        const data = list.map(item => {
          // console.log('Object.values(item) --------', Object.values(item))
          return Object.values(item)
        })
        // console.log('data----', data, 'header---------', header)
        return { data: data, header: header }
      }
      return
    },
    // 点击了分配角色 接收了一个该角色被点击的id根据id判断是给那个角色分配权限
    clickAssign(id) {
      this.roleId = id
      this.showDialogRole = true
    }

  }
}
</script>
